<template>
  <el-form-item>
    <el-button @click="onSubmit">保存</el-button>
  </el-form-item>
  <!-- 生产订单表 -->
  <h2 style="margin-left: 400px;">生产订单</h2>
  <div>
    <table class="order-table">
      <tr>
        <th colspan="6">基本信息</th>
      </tr>
      <tr>
        <td style="width: 100px;">单据主题：</td>
        <td>
          <el-input v-model="form.documentsName" placeholder="请输入单据主题" style="width: 150px;" />
        </td>
        <td style="width: 100px;">单据编号：</td>
        <td>
          <el-input v-model="form.documentsNum" placeholder="请输入单据编号" style="width: 150px;" disabled />
        </td>
        <td></td>
        <td></td>
      </tr>
      <tr>
        <td style="width: 100px;">制单人员：</td>
        <td>
          <el-input placeholder="请输入制单人员" v-model="form.personnel" style="width: 150px;" disabled />
        </td>
        <td style="width: 100px;">制单日期：</td>
        <td>
          <el-input :value="currentDate" style="width: 150px;" disabled />
        </td>
        <td style="width: 100px;">关联项目：</td>
        <td>
          <el-form-item prop="projectId">
            <el-input placeholder="请输入" v-model="form.projectDisplay" required>
              <template #suffix>
                <el-button size="mini" :icon="Search" @click="openAssociatedItemDialog">
                  <i class="el-icon-search"></i>
                </el-button>
              </template>
            </el-input>
          </el-form-item>
        </td>
      </tr>
      <tr>
        <td>备注：</td>
        <td colspan="5">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注信息" />
        </td>
      </tr>
    </table>
  </div>

  <!-- 订单明细表 -->
  <div>
    <div class="header">
      <h2 style="margin-left: 400px;">订单明细</h2>
      <button @click="addNewRow">新增行</button>
    </div>
    <table>
      <thead class="order-table">
        <tr>
          <th>序号</th>
          <th>产品名称</th>
          <th>产品编号</th>
          <th>规格型号</th>
          <th>单位</th>
          <th>订单数量</th>
          <th>生产类型</th>
          <th>计划开工日期</th>
          <th>计划完工日期</th>
          <th>交货日期</th>
          <th>备注</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(row, index) in rows" :key="row.ordersId">
          <td>{{ index + 1 }}</td>
          <td><input v-model="row.productName" type="text" style="width: 70px;" disabled /></td>
          <td><input v-model="row.productNumber" type="text" style="width: 70px;" disabled /></td>
          <td><input v-model="row.specifications" type="text" style="width: 70px;" disabled /></td>
          <td><input v-model="row.unit" type="text" style="width: 70px;" disabled /></td>
          <td><input v-model="row.orderQuantity" type="number" style="width: 70px;" disabled /></td>
          <td><input v-model="row.typeProduction" type="text" style="width: 70px;" disabled /></td>
          <td><input v-model="row.startDate" type="date" style="width: 70px;" disabled /></td>
          <td><input v-model="row.completionDate" type="date" style="width: 70px;" disabled /></td>
          <td><input v-model="row.deliveryDate" type="date" style="width: 70px;" disabled /></td>
          <td><input v-model="row.remark" type="text" style="width: 70px;" disabled /></td>
          <td>
            <button @click="deleteRow(row.documentsId)">删除</button>
          </td>
        </tr>
        <tr v-if="isAdding">
          <td>{{ rows.length + 1 }}</td>
          <td><input v-model="newRow.productName" type="text" style="width: 70px;"  @click="openshoppingDialog()"/></td>
          <td><input v-model="newRow.productNumber" type="text" style="width: 70px;" /></td>
          <td><input v-model="newRow.specifications" type="text" style="width: 70px;" /></td>
          <td><input v-model="newRow.unit" type="text" style="width: 70px;" /></td>
          <td><input v-model="newRow.orderQuantity" type="number" style="width: 70px;" /></td>
          <td>
            <select v-model="newRow.typeProduction" style="width: 70px;">
              <option value="自制">自制</option>
              <option value="委外">委外</option>
            </select>
          </td>
          <td><input v-model="newRow.startDate" type="date" style="width: 70px;" /></td>
          <td><input v-model="newRow.completionDate" type="date" style="width: 70px;" /></td>
          <td><input v-model="newRow.deliveryDate" type="date" style="width: 70px;" /></td>
          <td><input v-model="newRow.remark" type="text" style="width: 70px;" /></td>
          <td>
            <button @click="saveNewRow">保存</button>
            <button @click="cancelAddRow">取消</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>

  <!-- 附件部分 -->
  <div class="attachment-section">
    <h4 class="sub-title">附件管理</h4>
    <el-form ref="formRef" :model="formData" label-width="100px">
      <el-form-item label="选择文件">
        <el-upload ref="uploadRef" action="https://localhost:7269/api/FileUpload/UploadFile" :headers="headers"
          :on-success="handleSuccess" :on-error="handleError" :show-file-list="false" :http-request="customRequest">
          <el-button type="primary">选择文件</el-button>
        </el-upload>
      </el-form-item>
    </el-form>
  </div>

  <!-- 关联项目选择对话框 -->
  <el-dialog v-model="associatedItemDialogVisible" width="500" title="关联项目选择" append-to-body>
    <el-table :data="associatedItems" highlight-current-row border size="small"
      @current-change="handleAssociatedItemChange" @row-click="handleRowClick">
      <el-table-column type="index" label="序号" />
      <el-table-column prop="projectName" label="项目名称" />
      <el-table-column prop="projectNum" label="项目编号" />
      <el-table-column prop="projectTime" label="日期" />
      <el-table-column prop="projectPeople" label="负责人" />
    </el-table>
    <template #footer>
      <el-button @click="pickAssociatedItem">确定</el-button>
    </template>
  </el-dialog>

  <!-- 关联产品名称 -->
  <el-dialog v-model="shoushopping" title="商品列表" width="800">
    <el-table :data="getshoppinglist" @row-click="handleshoppingRowClick">
      <el-table-column property="productsName" label="商品名称" width="150" />
      <el-table-column property="productsNumber" label="编号" width="200" />
      <el-table-column property="productsType" label="规格型号" />
      <el-table-column property="productsUnit" label="单位" />
    </el-table>
  </el-dialog>

</template>

<script setup>
import { ref, reactive, onMounted, toRaw } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { useRoute } from 'vue-router';
import axios from 'axios';
import router from '@/router';
import { useCounterStore } from "@/stores/counter";
import { Wread, Wwrite } from "@/axios/axiosHelper";
import { Delete, Edit, Search, Share, Upload } from '@element-plus/icons-vue';

const store = useCounterStore();

const shoushopping = ref(false);

//弹出商品选择框
const openshoppingDialog = () => {
  shoushopping.value = true;
}

// 处理表格行点击事件
const handleshoppingRowClick = (row) => {
  const id = row.productsId;
  console.log('点击行的 id 为:', id);
  // 这里可以添加你需要的其他逻辑，比如跳转到详情页等
  shoushopping.value = false;
  conditionshopping(id); // 调用条件查询商品的方法
};

//存储条件查询出来的商品数据
const conditionshoppinglist = ref([
  {
    productsId: 0,
    productsName: "",
    productsNumber: "",
    productsType: "",
    productsUnit: "",
    productsNum: "",
    price: 0,
    remark: "",
    del: false
  }
]);

//条件查询商品
const conditionshopping = (id) => {
  Wread.get('/w2-read/api/Products/ShowProducts', {
    params: {
      productsId: id
    }
  })
    .then(response => {
      conditionshoppinglist.value = response.data.data;
      if (conditionshoppinglist.value.length > 0) {
        const product = conditionshoppinglist.value[0];
        newRow.value.productName = product.productsName;
        newRow.value.productNumber = product.productsNumber;
        newRow.value.specifications = product.productsType;
        newRow.value.unit = product.productsUnit;
      }
    })
}

//弹出框的商品显示数据
const getshoppinglist = ref([{
  productsId: 0,
  productsName: "",
  productsNumber: "",
  productsType: "",
  productsUnit: "",
  productsNum: "",
  price: 0,
  remark: "",
  del: false
}]);

//弹出框的商品显示
const getshopping = () => {
  Wread.get('/w2-read/api/Products/GetProducts')
    .then(response => {
      getshoppinglist.value = response.data.data;
    })
}

const formRef = ref(null);
const uploadRef = ref(null);
const formData = ref({});
const message = ref('');
const messageType = ref('');

const headers = {
  'Content-Type': 'multipart/form-data'
};

const customRequest = async (options) => {
  const formData = new FormData();
  formData.append('file', options.file);
  try {
    const response = await axios.post(options.action, formData, {
      headers: headers
    });
    options.onSuccess(response.data);
    if (response.data) {
      ElMessage.success('上传成功');
    } else {
      ElMessage.error('上传失败');
    }
  } catch (error) {
    handleError(error);
  }
};

const handleError = (error) => {
  message.value = '上传失败: ' + (error.response?.data?.error || error.message);
  messageType.value = 'error';
  console.error('上传错误:', error);
};

const submitForm = () => {
  uploadRef.value.submit();
};

// 生成单据编号的函数
const generateDocumentsNum = () => {
  let letters = '';
  for (let i = 0; i < 4; i++) {
    letters += String.fromCharCode(65 + Math.floor(Math.random() * 26));
  }
  let numbers = '';
  for (let i = 0; i < 10; i++) {
    numbers += Math.floor(Math.random() * 10);
  }
  return letters + numbers;
};

// 关联项目数据
const associatedItems = ref([{}]);

const guanlianxiangmu = () => {
  Wread.get('/w-read/api/Project/ShowProject')
    .then(res => {
      if (res.data && res.data.data) {
        associatedItems.value = res.data.data;
        console.log("查询关联项目数据", associatedItems.value);
      } else {
        console.error('接口返回数据格式不正确');
        ElMessage.error('接口返回数据格式不正确，请检查接口');
      }
    })
    .catch(error => {
      console.error('获取关联项目数据失败:', error);
      ElMessage.error('获取关联项目数据失败，请检查网络或联系管理员');
    });
};

// 生产订单数据
const form = reactive({
  documentsName: '',
  documentsNum: '',
  projectId: '',
  projectDisplay: '', // 新增属性，用于显示所选项目的名字
  remark: '',
  personnel: store.counterStore.userName,
  documentsId: null,
});

// 订单明细数据
const rows = ref([]);
const isAdding = ref(false);
const newRow = ref({
  ordersId: '',
  productName: '',
  productNumber: '',
  specifications: '',
  unit: '',
  orderQuantity: '',
  typeProduction: '',
  startDate: '',
  completionDate: '',
  deliveryDate: '',
  remark: '',
  documentsId: null,
});
const route = useRoute();

// 生产订单方法
const onSubmit = () => {
  if (!form.documentsName || !form.documentsNum || !form.projectId) {
    ElMessage.error('单据主题、单据编号和关联项目为必填项');
    return;
  }
  Wwrite
    .post('w-write/api/Documents/CreateDocuments', form)
    .then((res) => {
      if (res.data.code === 100) {
        form.documentsId = res.data.data.documentsId;
        ElMessage.success(res.data.msg);
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .catch((error) => {
      if (error.response) {
        ElMessage.error(`请求出错，状态码：${error.response.status}`);
      } else if (error.request) {
        ElMessage.error('请求已发送，但没有收到响应');
      } else {
        ElMessage.error('请求出错，请稍后重试');
      }
      console.error(error);
    });
};

// 自动显示时间年月日
const currentDate = ref('');
const getCurrentDate = () => {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
};
onMounted(() => {
  getshopping();
  guanlianxiangmu();
  currentDate.value = getCurrentDate();
  // 调用生成单据编号的函数并赋值
  form.documentsNum = generateDocumentsNum();
});

// 新增行
const addRow = () => ({
  ordersId: '',
  productName: '',
  productNumber: '',
  specifications: '',
  unit: '',
  orderQuantity: '',
  typeProduction: '',
  startDate: '',
  completionDate: '',
  deliveryDate: '',
  remark: '',
  documentsId: '',
});

const addNewRow = () => {
  newRow.value = addRow();
  isAdding.value = true;
};

// 保存新增行
const saveNewRow = () => {
  if (!newRow.value.productName || !newRow.value.productNumber || !newRow.value.orderQuantity) {
    ElMessage.error('产品名称、产品编号和订单数量为必填项');
    return;
  }
  newRow.value.documentsId = form.documentsId;
  Wwrite
    .post('/w-write/api/Orders/CreateOrders', toRaw(newRow.value))
    .then((res) => {
      if (res.data.code === 100) {
        ElMessage.success(res.data.msg);
        rows.value.push({ ...newRow.value });
        isAdding.value = false;
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .catch((error) => {
      if (error.response) {
        ElMessage.error(`请求出错，状态码：${error.response.status}`);
      } else if (error.request) {
        ElMessage.error('请求已发送，但没有收到响应');
      } else {
        ElMessage.error('请求出错，请稍后重试');
      }
      console.error(error);
    });
};

// 取消新增行
const cancelAddRow = () => {
  isAdding.value = false;
};

// 删除
const deleteRow = (documentsId) => {
  Wwrite.post('w-write/api/Orders/DelOrders', {
    documentsId: documentsId
  })
    .then(res => {
      if (res.data.code === 100) {
        ElMessage.success(res.data.msg);
        // 从 rows 中移除已删除的行
        rows.value = rows.value.filter(row => row.documentsId !== documentsId);
      } else {
        ElMessage.error(res.data.msg);
      }
    })
    .catch(error => {
      if (error.response) {
        ElMessage.error(`请求出错，状态码：${error.response.status}`);
      } else if (error.request) {
        ElMessage.error('请求已发送，但没有收到响应');
      } else {
        ElMessage.error('请求出错，请稍后重试');
      }
      console.error(error);
    });
};

const associatedItemDialogVisible = ref(false);
const currentAssociatedItem = ref({});

// 打开关联项目选择对话框
const openAssociatedItemDialog = () => {
  associatedItemDialogVisible.value = true;
};

// 当前选中的关联项目行
const handleAssociatedItemChange = (val) => {
  currentAssociatedItem.value = val;
};

// 行点击事件处理函数
const handleRowClick = (row) => {
  currentAssociatedItem.value = row;
};

const fan = ref("");
// 选择关联项目
const pickAssociatedItem = () => {
  if (currentAssociatedItem.value) {
    form.projectId = currentAssociatedItem.value.projectId;
    form.projectDisplay = currentAssociatedItem.value.projectName; // 更新显示的值
    form.projectId = currentAssociatedItem.value.projectId; // 修改为 form.projectId
    associatedItemDialogVisible.value = false;
  }
};

const batchUpload = () => {
  ElMessageBox.confirm('确认上传选中文件？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.info('批量上传功能待完善具体逻辑');
  });
};
</script>

<style scoped>
.order-table {
  border-collapse: collapse;
  width: 100%;
}

.order-table th,
.order-table td {
  border: 1px solid #ccc;
  padding: 8px;
  text-align: left;
}

.order-table th {
  background-color: #f2f2f2;
}
</style>

<style scoped>
#app {
  padding: 20px;
}
</style>    